package com.zja.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author JA
 * @date: 2025/5/4
 * description:
 */
public class ServletUtil {
    private static final ObjectMapper mapper = new ObjectMapper();
    /**
     * 将对象以 JSON 格式写入响应中
     * @param resp HttpServletResponse
     * @param obj 任意对象，会被序列化为 JSON
     */
    public static void writeJsonResponse(HttpServletResponse resp, Object obj) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.write(JsonUtil.toJson(obj));
        out.flush();
        out.close();
    }

    /**
     * 从请求体中读取 JSON 数据并反序列化为指定类型的 Java 对象
     *
     * @param request HttpServletRequest，请求对象，包含 JSON 请求体
     * @param clazz   目标对象的类型 Class，用于反序列化
     * @param <T>     泛型类型参数，表示返回的对象类型
     * @return 反序列化后的 Java 对象
     * @throws IOException 如果读取请求体或解析 JSON 时发生 IO 异常
     */
    public static <T> T readJsonBody(HttpServletRequest request, Class<T> clazz) throws IOException {
        return mapper.readValue(request.getInputStream(), clazz);
    }
}
